package com.abc.cloud.controller;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.abc.cloud.common.utils.*;
import com.abc.cloud.dto.user.UserInfoAndRole;
import com.abc.cloud.dto.user.UserKeyCode;
import com.abc.cloud.dto.user.UserSpace;
import com.abc.cloud.entity.LoginLogEntity;
import com.abc.cloud.entity.UserRoleRelationEntity;
import com.abc.cloud.service.*;
import com.abc.cloud.vo.file.FileUpload;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import com.abc.cloud.entity.UserEntity;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;

import static com.abc.cloud.common.constants.Constants.CAPTCHA_CODE;


@Slf4j


/**
 * 用户表
 *
 * @author LiJunXi
 * @email 2770063826@qq.com
 * @date 2023-10-27 13:09:54
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private UserRoleRelationService userRoleRelationService;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private MenuService menuService;
    @Autowired
    private FileService fileService;
    @Autowired
    private LoginLogService loginLogService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    public Result list(@RequestParam Map<String, Object> params){
        PageUtil page = userService.queryPage(params);

        return Result.success(page, "page");
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    public Result info(@PathVariable("id") Long id){
		UserEntity user = userService.getById(id);
        return Result.success(user, "user");
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    public Result save(@RequestBody UserEntity user){
		userService.save(user);

        return Result.success(null, "");
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public Result update(@RequestBody UserEntity user){
		userService.updateById(user);

        return Result.success(null, "");
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public Result delete(@RequestBody Long[] ids){
		userService.removeByIds(Arrays.asList(ids));

        return Result.success(null, "");
    }
    // 用户登录
    @Transactional
    @RequestMapping("/userLogin")
    public Result userLogin(@RequestBody UserEntity user, HttpServletRequest request){
        log.info("前端传过来的 user = {}", user);
        String password = user.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        user.setPassword(password);
        log.info("MD5加密后的 user = {}", user);
        UserEntity userInfo = userService.userLogin(user);
        if(userInfo != null){
            boolean isUser = userRoleRelationService.isUser(userInfo.getId());//true为user
            if(!isUser)return Result.fail(null, "登录失败,请联系管理员");
            String jwt = JwtUtil.createToken(userInfo.getId(),userInfo.getUsername());
            log.info("jwt = {}",jwt);
            // userInfo.setLastLoginTime(new Date());          //登录成功，更新最近登录
            userService.setLastLoginTime(userInfo.getId());
            LoginLogEntity loginLogEntity = new LoginLogEntity();
            loginLogEntity.setIpAddress(IpUtil.getIpAddr(request));
            loginLogEntity.setUserId(userInfo.getId());
            loginLogEntity.setLoginTime(new Date());
            loginLogEntity.setUsername(userInfo.getUsername());
            System.out.println("loginLogEntity = " + loginLogEntity);
            loginLogService.save(loginLogEntity);
//            loginLogService.addLog(user.getId());
            return Result.success(jwt, "成功");
        }
        return Result.fail(null,"账号或密码错误" );

    }
    //管理员登录
    @RequestMapping("/adminLogin")
    public Result adminLogin(@RequestBody UserEntity user){
        log.info("前端传过来的 user = {}", user);
        String password = user.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        user.setPassword(password);
        log.info("MD5加密后的 user = {}", user);
        UserEntity adminInfo = userService.userLogin(user);
        if(adminInfo != null){
            boolean isAdmin = userRoleRelationService.isAdmin(adminInfo.getId());//true为user
            if(!isAdmin)return Result.fail(null, "登录失败,请联系管理员");
            String jwt = JwtUtil.createToken(adminInfo.getId(),adminInfo.getUsername());
            log.info("jwt = {}",jwt);
            return Result.success(jwt, "成功");
        }
        return Result.fail(null,"账号或密码错误" );
    }
//    注册
    @RequestMapping("/userRegister")
    public Result userRegister(@RequestBody UserKeyCode user){

        log.info("前端传过来的 user = {}", user);
        String redisCode = redisTemplate.opsForValue().get(CAPTCHA_CODE + user.getKey());
        if(redisCode != null)redisCode = redisCode.toLowerCase();
        log.info("redisKey = {}", redisCode);
        if(user.getCode() == null)return Result.fail(null, "请输入验证码");
        if(redisCode == null)
            return Result.fail(null, "验证码错误");
            log.info("验证码过期");
        if (!redisCode.equals(user.getCode().toLowerCase())) {
            return Result.fail(null, "验证码错误");
        }
        String message =  userService.addUser(user);
        if(message == null)return Result.success(null, "注册成功");
        return Result.fail(null,message);
    }



    //获取用户信息(用户)
    @RequestMapping("/UserInfo")
    public Result getUserInfoRole(){
        Long id = UserHolder.getUser().getId();
        UserInfoAndRole userInfoRole = userService.getUserInfoRole(id);
        return Result.success(userInfoRole, "成功");
    }

    //用户更新nickname and gender(用户)
    @RequestMapping("/info/save")
    public Result updateUserInfo(@RequestBody Map<String, Object> requestBody){

        log.info("requestBody = {}", requestBody);
        String nickName = (String) requestBody.get("nickName");
//        Integer gender = Integer.parseInt((String)requestBody.get("gender"));
        Integer gender = (Integer)requestBody.get("gender");
        log.info("nickName = {} ,  gender = {}", nickName,gender);
        if(gender != 1 && gender != 2)return Result.fail(null, "保存失败");
        UserEntity user = new UserEntity();
        user.setId(UserHolder.getUser().getId());
        user.setNickname(nickName);
        user.setGender(gender);

        userService.updateById(user);
        return Result.success(null, "success");
    }
    //用户更新头像
    @RequestMapping("/uploadAvatar")
    public Result uploadAvatar(MultipartFile file){
        Long userId = UserHolder.getUser().getId();
        String username = UserHolder.getUser().getUsername();
        System.out.println(file.getOriginalFilename());
        String newAvatarUrl = fileService.upload(file, userId,username);
        UserEntity userEntity = new UserEntity();
        userEntity.setId(userId);
        userEntity.setAvatar(newAvatarUrl);
        userService.updateById(userEntity);
        return Result.success(null,"上传成功");
    }

    // 获取用户空间
    @GetMapping("/getSpace")
    public Result<UserSpace> getSpace(){
        Long userId = UserHolder.getUser().getId();
        return Result.success(userService.getSpace(userId), "获取成功");
    }

    //查询用户信息(包含身份 and menu)(管理员)
    @RequestMapping("/admin/UserInfo")
    public Result getUserInfoRole(@RequestParam(name = "id", required = false) Long id){
        log.info("id = {}",id);
        if (id == null) id = UserHolder.getUser().getId();
        UserInfoAndRole userInfoRole = userService.getUserInfoRole(id);
        userInfoRole.setMenuList(menuService.queryUserMenuList(id));
        return Result.success(userInfoRole, "成功");
    }

    //管理员根据username Or nickname 查询用户
    @RequestMapping("/admin/UserList")
    public Result<PageUtil> getUserList(@RequestParam Map<String, Object> params){
        System.out.println("params = " + params);
        PageUtil pageUtil = userService.getUserList(params);
        return Result.success(pageUtil, "success");
    }
    //管理员update  UserInfo
    @RequestMapping("/admin/saveUser")
    public Result adminUpdateUserInfo(@RequestBody UserEntity user){
        System.out.println("user = " + user);
//        PageUtil pageUtil = userService.getUserList(params);
        userService.updateById(user);
        return Result.success(null, "保存成功");
    }
    //管理员修改 UserStatus
    @RequestMapping("/admin/updateUserStatus/{status}")
    public Result adminUpdateUserStatus(@RequestBody List<Long> userIds,
                                        @PathVariable("status") Integer status){
        userService.updateUserStatus(userIds,status);
        return Result.success(null, "修改成功");
    }

    //管理员新增用户
    @RequestMapping("/admin/createUser")
    public Result createUser(@RequestBody UserKeyCode user){
        String message = userService.addUser(user);
        if(message == null)return Result.success(null, "创建成功");
        return  Result.fail(null, message);
    }

}
